package cn.zxcoder.controller.user;

import cn.zxcoder.Tools.ToolUtil;
import cn.zxcoder.entity.AccountRole;
import cn.zxcoder.entity.Res;
import cn.zxcoder.entity.RoleRight;
import cn.zxcoder.entity.SystemManage.Dept;
import cn.zxcoder.entity.SystemManage.Right;
import cn.zxcoder.entity.SystemManage.Role;
import cn.zxcoder.entity.login.Account;
import cn.zxcoder.service.*;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zx
 * @since 2023-05-12
 */
@RestController
@Api(tags = "用户管理控制器")
@RequestMapping("/api/User")
public class UserController {

    @Resource
    RedisTemplate redisTemplate;

    @Autowired
    IAccountService iAccountServiceIml;

    @Autowired
    IRightService iRightServiceIml;

    @Autowired
    IRoleService iRoleServiceIml;

    @Autowired
    IMenuService iMenuServiceIml;

    @Autowired
    IDeptService iDeptServiceIml;

    @Autowired
    IRoleRightService iRoleRightServiceIml;

    @Autowired
    IAccountRoleService iAccountRoleServiceIml;

    @ApiOperation(value = "获取此code页面的所有操作权限")
    @PostMapping("/page/opRight")
    @Transactional(readOnly = true)
    public Res getOpRight(@RequestParam String code,@RequestParam String token) {

        String roleId = JSON.parseObject(token, Account.class).getRoleId();//当前登录用户的角色id

        ArrayList<String> res = new ArrayList<>();

        //通过角色id获取所有的操作权限
        Role role = iRoleServiceIml.getById(Integer.parseInt(roleId));
        String roleRights = role.getRoleRights();
        String[] split = roleRights.split(",");
        for (String s : split) {
            Right right = iRightServiceIml.getById(Integer.parseInt(s));

            String rightCode = right.getRightCode();
            String[] strings = rightCode.split(":");
            if (right.isOp() && strings[1].equals(code)) {
                res.add(strings[2]);
            }
        }

        return new Res(true, JSON.toJSONString(res), "查询所有操作权限成功");

    }


    @ApiOperation(value = "获取所有用户列表")
    @PostMapping("/list")
    @Transactional(readOnly = true)
    public Res getUser(@RequestParam String page, @RequestParam String limit, @RequestParam String userName,
                        @RequestParam String userMobile,@RequestParam String status) {

        Page<Account> page1 = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        if (!userName.equals("")) {
            wrapper.like("username", userName);
        }
        if (!userMobile.equals("")) {
            wrapper.like("phone", userMobile);
        }
        if (!status.equals("")) {
            wrapper.eq("status", status);
        }
        Page<Account> res = iAccountServiceIml.page(page1, wrapper);

        res.getRecords().forEach(account -> {
            if (account.getDept() != null) {
                account.setDeptName(iDeptServiceIml.getById(account.getDept()).getName());
            }
            if (account.getRoleId() != null) {
                account.setRoleName(iRoleServiceIml.getById(account.getRoleId()).getRoleName());
            }
        });

        return new Res(true, JSON.toJSONString(res), "获取所有用户列表成功");
    }


    @ApiOperation(value = "保存或者编辑")
    @PostMapping("/save")
    @Transactional(readOnly = true)
    public Res saveUser(@RequestParam String userId, @RequestParam String userName, @RequestParam String userRealName,
                         @RequestParam boolean issave,@RequestParam String userMobile,@RequestParam String userEmail,
                        @RequestParam String userSex) {



        if (issave) {
            Account account = new Account();
            account.setUsername(userName);
            account.setName(userRealName);
            account.setPhone(userMobile);
            account.setMail(userEmail);
            account.setSex(userSex);
            account.setEditTime(new Date());
            System.out.println(account);

            boolean save = iAccountServiceIml.save(account);
            return new Res(save, null, save ? "保存用户信息成功" : "保存用户信息失败");
        } else {
            UpdateWrapper<Account> accountUpdateWrapper = new UpdateWrapper<>();
            accountUpdateWrapper.set("username", userName);
            accountUpdateWrapper.set("name", userRealName);
            accountUpdateWrapper.set("phone", userMobile);
            accountUpdateWrapper.set("mail", userEmail);
            accountUpdateWrapper.set("sex", userSex);
            accountUpdateWrapper.set("editTime", new Date());
            accountUpdateWrapper.eq("id", userId);
            boolean update = iAccountServiceIml.update(accountUpdateWrapper);
            return new Res(update, null, update ? "编辑用户信息成功" : "编辑用户信息失败");
        }
    }

    @ApiOperation(value = "权限管理-删除用户")
    @DeleteMapping("/delete/{id}")
    @Transactional

    public Res deleteUser(@PathVariable String id) {
        boolean b = iAccountServiceIml.removeById(Integer.parseInt(id));
        return new Res(b, null, b ? "删除用户成功" : "删除用户失败");

    }

    @ApiOperation(value = "重新设置用户密码为123456")
    @PostMapping("/pwd")
    @Transactional

    public Res reSetPwd(@RequestParam String userId) {

        UpdateWrapper<Account> wrapper = new UpdateWrapper<>();
        wrapper.set("password", "123456");
        wrapper.eq("id", userId);
        boolean update = iAccountServiceIml.update(wrapper);

        return new Res(update, null, update ? "重置密码成功" : "重置密码失败");
    }



    @ApiOperation(value = "修改用户状态")
    @PostMapping("/lock")
    @Transactional

    public Res setLock(@RequestParam String lock,@RequestParam String userId) {

        UpdateWrapper<Account> wrapper = new UpdateWrapper<>();
        wrapper.set("status", lock);
        wrapper.eq("id", userId);
        boolean update = iAccountServiceIml.update(wrapper);

        return new Res(update, null, update ? "修改用户状态成功" : "修改用户状态失败");

    }


    @ApiOperation(value = "获取用户权限")
    @GetMapping("/right/tree/{id}")
    @Transactional

    public Res getUserRight(@PathVariable String id) {
//        Account accoount = iAccountServiceIml.getById(Integer.parseInt(id));(一对多)
//        String roleId = accoount.getRoleId();
//
//        if (roleId == null) {
//            return new Res(false, null, "此用户还没有配置权限呢");
//        }
//        //找到指定的role
//        Role role = iRoleServiceIml.getById(Integer.parseInt(roleId));
//        //查询此角色role的权限字符串
//        String roleRights = role.getRoleRights();

        QueryWrapper<AccountRole> accountRoleQueryWrapper = new QueryWrapper<>();
        accountRoleQueryWrapper.eq("account_Id", Integer.parseInt(id));
        Integer roleId = iAccountRoleServiceIml.getOne(accountRoleQueryWrapper).getRoleId();

        QueryWrapper<RoleRight> roleRightQueryWrapper = new QueryWrapper<>();
        roleRightQueryWrapper.eq("role_id", roleId);
        String roleRights = iRoleRightServiceIml.getOne(roleRightQueryWrapper).getRightsIds();



        //转换为权限id数组
        String[] strings = roleRights.split(",");
        List<Integer> ids = Arrays.stream(strings).map(Integer::parseInt).collect(Collectors.toList());

        //设置它的children数组属性
        List<Right> res = ToolUtil.setchildren(ids, iRightServiceIml);

        return new Res(true, JSON.toJSONString(res), "成功获取菜单权限");


    }

    @ApiOperation(value = "获取部门数据")
    @GetMapping("/Dept/list")
    @Transactional

    public Res getDept() {
        List<Dept> list = iDeptServiceIml.list();
        return new Res(true, JSON.toJSONString(list), "成功获取部门数据");

    }

    @ApiOperation(value = "保存部门数据")
    @PostMapping("/Dept/save")
    @Transactional

    public Res saveDept(@RequestParam String userIds, @RequestParam String deptId) {


        String[] ids = userIds.split(",");
        for (String id : ids) {

            UpdateWrapper<Account> wrapper = new UpdateWrapper<>();
            wrapper.set("dept", deptId);
            wrapper.eq("id", Integer.parseInt(id));
            boolean update = iAccountServiceIml.update(wrapper);
            if (!update) {
                return new Res(false, null, "保存部门数据失败");
            }
        }
        return new Res(true, null, "保存部门数据成功");

    }


    @ApiOperation(value = "强制用户下线")
    @GetMapping("/expire/{id}")
    @Transactional

    public Res setExpire( @PathVariable String id) {

        //用户下线操作
        UpdateWrapper<Account> wrapper = new UpdateWrapper<>();
        wrapper.set("status", "Y");
        wrapper.eq("id", Integer.parseInt(id));
        boolean update = iAccountServiceIml.update(wrapper);

        //删除对应的token
        redisTemplate.delete(iAccountServiceIml.getById(Integer.parseInt(id)).getUsername());

        return new Res(update, null, update ? "已经成功强制用户下线" : "强制用户下线失败");
    }

    @ApiOperation(value = "刷新缓存")
    @GetMapping("/flashCache")
    @Transactional

    public Res flashCache(@RequestParam String username,@RequestParam String token) {

     //刷新缓存操作
        //删除Jedis的数据
        ToolUtil.jedis.del(username);
        ToolUtil.jedis.del(token);
        return new Res(true, null, "已经成功刷新缓存");

    }

    @ApiOperation(value = "查询所有的角色信息数据")
    @PostMapping("/role/list")
    @Transactional(readOnly = true)
    public Res getRole() {

        List<Role> list = iRoleServiceIml.list();
        return new Res(true, JSON.toJSONString(list), "查询所有的角色信息数据成功");

    }

    @ApiOperation(value = "配置角色")
    @PostMapping("/role/save")
    @Transactional
    public Res setRole(@RequestParam String userId, @RequestParam String roleId) {


        UpdateWrapper<Account> wrapper = new UpdateWrapper<>();
        wrapper.set("role_id", roleId);
        wrapper.eq("id", Integer.parseInt(userId));
        boolean update = iAccountServiceIml.update(wrapper);
        if (!update) {
            return new Res(false, null, "配置角色失败");
        }
        return new Res(true, null, "配置角色成功");

    }



}
